//
//  BKEmptyMsgView.m
//  AFNetworking
//
//  Created by baboy on 2019/2/18.
//

#import <Foundation/Foundation.h>
#import "BKEmptyMsgView.h"
#import "UILabel+x.h"
#import "NSAttributedString+x.h"

#define EMPTY_MSG_TEXT_FONT [UIFont systemFontOfSize:12]
#define EMPTY_MSG_TEXT_COLOR [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1]
#define EMPTY_MSG_TEXT_SHADOW_COLOR [UIColor colorWithRed:1 green:1 blue:1 alpha:1]

@interface BKEmptyMsgView(x)
- (void)createWithMessage:(NSString *)msg withNetworkIndicator:(BOOL)withIndicator icon:(NSString *)iconName;
@end

@implementation BKEmptyMsgView

- (id) initWithFrame:(CGRect)frame withMessage:(NSString *)msg withNetworkIndicator:(BOOL)withIndicator icon:(NSString *)iconName{
    if (self = [super initWithFrame:frame]) {
        [self createWithMessage:msg withNetworkIndicator:withIndicator icon:iconName];
    }
    return self;
}
- (void)createWithMessage:(NSString *)msg withNetworkIndicator:(BOOL)withIndicator icon:(NSString *)iconName{
    float w = self.bounds.size.width, h = self.bounds.size.height;
    
    UIImage *icon = [UIImage imageNamed:iconName];
    CGRect iconFrame = CGRectMake((w-icon.size.width)/2, h*0.35-icon.size.height/2, icon.size.width, icon.size.height);
    UIButton *btn = [[UIButton alloc] initWithFrame:iconFrame];
    [btn setImage:icon forState:UIControlStateNormal];
    self.icon = btn;
    [self addSubview:btn];
    float indicatorWidth = withIndicator?20:0;
    CGRect labelFrame = CGRectMake(0, iconFrame.origin.y+icon.size.height+10, w, 40);
    CGSize msgSize = [NSAttributedString sizeOfString:msg withFont:EMPTY_MSG_TEXT_FONT constrainedToSize:CGSizeMake(w, MAXFLOAT)];
    labelFrame.size.width = msgSize.width;
    labelFrame.origin.x = (w-labelFrame.size.width)/2+indicatorWidth/2;
    UILabel *msgLabel = createLabel(labelFrame, EMPTY_MSG_TEXT_FONT, nil, EMPTY_MSG_TEXT_COLOR, EMPTY_MSG_TEXT_SHADOW_COLOR, CGSizeMake(0, 1), NSTextAlignmentCenter, 0, NSLineBreakByTruncatingTail);
    msgLabel.text = msg;
    self.msgLabel = msgLabel;
    
    [self addSubview:msgLabel];
    
    if (withIndicator) {
        UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        CGRect indicatorFrame = CGRectMake(labelFrame.origin.x - 24, labelFrame.origin.y+(labelFrame.size.height-msgSize.height)/2, 20, 20);
        indicator.frame = indicatorFrame;
        [indicator startAnimating];
        [self addSubview:indicator];
    }
}
- (void) addTarget:(id)target action:(SEL)action{
    if (target && action) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:action];
        [self addGestureRecognizer:tap];
    }
}

@end
